package com.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api("员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @ApiOperation("员工登录")
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

       // Employee employee = employeeService.login(employeeLoginDTO);

        LambdaQueryWrapper<Employee> empDtoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        empDtoLambdaQueryWrapper.eq(Employee::getUsername,employeeLoginDTO.getUsername()).last("limit 1");
        Employee employee = employeeService.getOne(empDtoLambdaQueryWrapper);
        String password = DigestUtils.md5DigestAsHex(employeeLoginDTO.getPassword().getBytes());
        if(employee==null){
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }else{
            if(!employee.getPassword().equals(password)){
                //密码错误
                throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
            }else{
                if(employee.getStatus()== StatusConstant.DISABLE){
                    //账号被锁定
                    throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
                }else{

                    //登录成功后，生成jwt令牌
                    Map<String, Object> claims = new HashMap<>();
                    claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
                    String token = JwtUtil.createJWT(
                            jwtProperties.getAdminSecretKey(),
                            jwtProperties.getAdminTtl(),
                            claims);

                    EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                            .id(employee.getId())
                            .userName(employee.getUsername())
                            .name(employee.getName())
                            .token(token)
                            .build();

                    return Result.success(employeeLoginVO);
                }
            }
        }
    }

    /**
     * 退出
     *
     * @return
     */
    @ApiOperation("员工登出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }


    /**
     * 新增员工
     * @param employeeDTO
     * @return
     */
    @ApiOperation("新增员工")
    @PostMapping
    public Result save(@RequestBody EmployeeDTO employeeDTO){
//做异常处理比进行查询操作再判断更优
        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        //设定默认值
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employee.setStatus(1);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //ThreadLocal在token校验时存下用户id，在这里取出
//        Long id = BaseContext.getCurrentId();
//        employee.setUpdateUser(id);
//        employee.setCreateUser(id);
        employeeService.save(employee);
        return Result.success() ;

    }


    /**
     * 员工分页查询
     */
    @ApiOperation("员工分页查询")
    @GetMapping("/page")
    public Result page(int page, int pageSize,String name){
        Page<Employee> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name!=null,Employee::getName,name);
        lambdaQueryWrapper.orderByDesc(Employee::getCreateTime);
        employeeService.page(pageInfo,lambdaQueryWrapper);
        return Result.success(pageInfo);
    }

    /**
     * 修改员工状态
     * @param status
     * @param id
     * @return
     */
    @ApiOperation("修改员工状态")
    @PostMapping("/status/{status}")
    public Result changeStatus(@PathVariable Integer status,Long id){
        Employee employee = employeeService.getById(id);
        log.info(employee.toString());
        employee.setStatus(status);
        employeeService.updateById(employee);
        return Result.success();
    }

    /**
     * 根据id查询员工
     */
    @ApiOperation("根据id查询员工")
    @GetMapping("/{id}")
    public Result getById(@PathVariable long id){
        if(id!=0){
            Employee employee = employeeService.getById(id);
            return Result.success(employee);
        }else {
            return Result.error("未找到该用户");
        }

    }

    /**
     * 修改员工信息
     * @return
     */
    @ApiOperation("修改员工信息")
    @PutMapping
    public Result update(@RequestBody Employee employee){
//        Long id = BaseContext.getCurrentId();
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(id);
        employeeService.updateById(employee);
        return Result.success("修改成功");
    }
}



